﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Configuration;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using XZL.Web.Biz;
using XZL.Web.Entity;
using XZL.Web.Da;
using XZL.Web.MVC.WXModel;

namespace XZL.Web.MVC.Controllers
{
    public class HomeController : Controller
    {
        string address = ConfigurationManager.AppSettings["ServerAddress"];
        string appid = ConfigurationManager.AppSettings["appid"];
        string appsecret = ConfigurationManager.AppSettings["appsecret"];
        string redirecturi = ConfigurationManager.AppSettings["redirecturi"];
        string appkey = ConfigurationManager.AppSettings["appkey"];
        string mchid = ConfigurationManager.AppSettings["mchid"];

        protected Hashtable Parameters = new Hashtable();  //请求参数集合

        /// <summary>
        /// 获取session数据
        /// </summary>
        /// <returns></returns>
        private UserInfo GetMyInfo()
        {
            UserInfo user = new UserInfo();
            if (HttpContext.Session["MyInfo"] != null)
            {
                user = HttpContext.Session["MyInfo"] as UserInfo;
            }
            else
            {
                string url = Request.Url.AbsoluteUri.ToString();

                string inviteID = "1";
                if (HttpContext.Session["InviteID"] != null)
                {
                    inviteID = HttpContext.Session["InviteID"].ToString();
                }
                string link1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirecturi;
                string link2 = "&response_type=code&scope=snsapi_userinfo&state=" + url;
                Response.Redirect(link1 + inviteID + link2);
            }
            return user;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Index()
        {
            string type = Request.QueryString["Type"];

            if (HttpContext.Session["MyInfo"] != null)
            {
                UserInfo user = HttpContext.Session["MyInfo"] as UserInfo;
                ViewBag.InviteID = user.UserNum;
            }

            else
            {
                string inviteID = Request.QueryString["InviteID"];
                if (inviteID == null || inviteID == "")
                {
                    inviteID = "1";
                }
                HttpContext.Session["InviteID"] = inviteID;
                ViewBag.InviteID = inviteID;
            }

            //直播|录播
            int tmp = 1;
            if (type != null)
            {
                if (int.TryParse(type, out tmp))
                {
                    tmp = Convert.ToInt32(type);
                }
            }
            ViewBag.IsLive = tmp;
            int? count = 0;
            List<Course> ls = CourseBiz.GetCourseList("", 0, 0, tmp, 1, 15, ref count);
            List<Proc_BannerInfo_SelectListResult> lsFlash = CourseBiz.GetBannerList();
            ViewBag.CourseList = ls;
            ViewBag.FlashList = lsFlash;

            return View();
        }

        /// <summary>
        /// 测试模版消息
        /// </summary>
        /// <returns></returns>
        public ActionResult SendMsg()
        {
            return View();
        }
        /// <summary>
        /// 测试模版消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendMsg(FormCollection fc)
        {
            List<Proc_CourseInfo_SelectStartListResult> ls = CourseBiz.GetStartCorseList();

            for (int i = 0; i < ls.Count; i++)
            {
                var data = WXTemplate.ClassWarn(ls[i].WeiXinName, "【" + ls[i].ItemName + "】", "【" + Convert.ToDateTime(ls[i].StartTime).ToString("yyyy-MM-dd HH:mm:ss") + "】", "如有任何问题，请联系客服：010-64756681 / 64758501。");

                SendTemplateMessageService.SendTemplateMessage("3uTEmR4egH-6LNcz3wkHv8QqJihep4NfUlcPxvcGLxs", ls[i].WeiXinID, "wfdot.com/Course/CourseInfo?CourseID=" + ls[i].CourseID, Get_Access_token(), data);
            }

            return View();
        }

        /// <summary>
        /// 获得access_token
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public string Get_Access_token()
        {
            WebClient webclient = new WebClient();
            string url = @"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret + "";
            byte[] bytes = webclient.DownloadData(url);//在指定的path上下载
            string result = Encoding.GetEncoding("utf-8").GetString(bytes);//转string
            JavaScriptSerializer js = new JavaScriptSerializer();
            AccessToken amodel = js.Deserialize<AccessToken>(result);//此处为定义的类，用以将json转成model
            string a_token = amodel.access_token;
            return a_token;
        }

        /// <summary>
        /// 测试分享
        /// </summary>
        /// <returns></returns>
        public ActionResult Shared()
        {
            wxshareHandler wxsh = new wxshareHandler();
            string token = wxsh.GetToken();
            string ticket = wxsh.GetTicket(token);
            int timestamp = wxsh.ConvertDateTimeInt(DateTime.Now);
            string nonceStr = wxsh.GenerateCheckCode(16);
            string url = address + "home/shared";
            string sign = wxsh.GetSignature(ticket, nonceStr, timestamp.ToString(), url);

            ViewBag.AppID = appid;
            ViewBag.Token = token;
            ViewBag.Ticket = ticket;
            ViewBag.Timestamp = timestamp.ToString();
            ViewBag.NonceStr = nonceStr;
            ViewBag.Sign = sign;
            ViewBag.Url = url;

            return View();
        }
    }
}